<template>
  <uv-toast ref="toastRef" position="top"></uv-toast>
  <view class="viewport">
    <!-- 表单 -->
    <view class="form">
      <!-- 表单内容 -->
      <view class="form-content">
        <view class="form-item">
          <text class="label">名称</text>
          <text class="account">{{ Note.name }}</text>
        </view>
        <view class="form-item">
          <text class="label">记录日期</text>
          <picker
            class="picker"
            mode="date"
            :value="Note.createDate"
            start="2000-01-01"
            :end="new Date()"
            @change="EventHandle"
          >
            <view v-if="Note.createDate">{{ Note.createDate }}</view>
            <view class="placeholder" v-else>请选择日期</view>
          </picker>
        </view>
        <textarea class="textarea" v-model="Note.remark" placeholder="记录果蔬的成长"></textarea>
        <!-- 上传照片，拍摄或者从相册选择 -->
        <uv-upload
          :fileList="fileList"
          name="1"
          maxCount="1"
          @afterRead="afterRead"
          @delete="deletePic"
          :previewFullImage="true"
        ></uv-upload>
      </view>
      <!-- 提交按钮 -->
      <button class="form-button" @click="save">保 存</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { insertOrUpdateNoteWithoutImgAPI } from '@/services/garden'
import dayjs from 'dayjs'
const toastRef = ref()
const Note = ref({
  remark: '',
  url: '',
  createDate: '',
  idGarden: '',
  id: '',
})

const EventHandle = (e) => {
  Note.value.createDate = e.detail.value
}

const save = async () => {
  if (!Note.value.remark) {
    await toastRef.value.show({
      type: 'error',
      message: '你还没有填入任何信息哦',
    })
    return
  }
  const formData = { ...Note.value }
  const url = fileList.value[0]?.url
  if (url && url.search('tmp') !== -1) {
    console.log(1)
    //临时文件才需要重新上传
    uni.uploadFile({
      url: '/garden/note',
      name: 'img',
      formData,
      filePath: fileList.value[0].url,
      success: (res) => {
        if (res.statusCode === 200) {
          const data = JSON.parse(res.data)
          if (data.code === 200) {
            toastRef.value.show({
              type: 'success',
              message: '保存成功',
            })
            setTimeout(() => {
              let pages = getCurrentPages()
              let prevPage = pages[pages.length - 2] //上一个页面
              prevPage.onLoad({ id: Note.value.idGarden, tot: 'garden' })
              uni.navigateBack({
                delta: 1,
              })
            }, 1500)
          }
        } else {
          toastRef.value.show({
            type: 'error',
            message: '保存失败',
          })
        }
      },
    })
  } else {
    if (!fileList.value[0]) {
      //如果用户删除了图片
      formData.url = ''
    }
    await insertOrUpdateNoteWithoutImgAPI(formData)
    toastRef.value.show({
      type: 'success',
      message: '保存成功',
    })
    setTimeout(() => {
      let pages = getCurrentPages()
      let prevPage = pages[pages.length - 2] //上一个页面
      prevPage.onLoad({ id: Note.value.idGarden, tot: 'garden' })
      uni.navigateBack({
        delta: 1,
      })
    }, 1500)
  }
}

onLoad((option) => {
  if (option.info) {
    let temp = JSON.parse(option.info)
    //已经存在的基础上进行更新
    Note.value = { ...temp }
    Note.value.createDate = dayjs(temp.createDate).format('YYYY-MM-DD')
    if (Note.value.url) {
      fileList.value.push({
        url: Note.value.url,
        status: 'success',
      })
    }
    return
  }
  //新建
  Note.value.idGarden = option.idGarden
  Note.value.name = option.name
  Note.value.createDate = dayjs(new Date()).format('YYYY-MM-DD')
})

// 定义响应式数据
const fileList = ref([])

// 删除图片
const deletePic = (event) => {
  fileList.value.splice(event.index, 1)
}

// 新增图片
const afterRead = async (event) => {
  console.log(event)
  let lists = [].concat(event.file)
  lists.forEach(async (item) => {
    fileList.value.push({
      ...item,
      status: 'success',
    })
  })
}
</script>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: auto 420rpx;
  background-repeat: no-repeat;
}

// 导航栏
.navbar {
  position: relative;

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }

  .back {
    position: absolute;
    height: 40px;
    width: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
// 表单
.form {
  background-color: #f4f4f4;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 20rpx 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 46rpx;
    // line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
      height: 46rpx;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }
    .placeholder {
      color: #808080;
    }
  }

  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #53a658;
  }
}

textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #64f76a;
  margin: 10px 0;
  box-sizing: border-box;
  border-radius: 8px;
}
</style>
